﻿<?PHP
include("../public/common.php");
$itemid = CheckUrlParamNoDie("itemid");
$tbid= CheckUrlParamNoDie("userid");	// 换成userid
$type = CheckUrlParamNoDie("type");
$callback = CheckUrlParamNoDie("callback");

function get_precent( $strHtml, $item_id, &$price, &$precent )
{
	$str_id = "id=". $item_id;
	$pos1 = stripos( $strHtml, $str_id );
	if( $pos1 === false )
		return false;
		
	$pos2 = stripos( $strHtml, "</em>%</span>", $pos1 );
	if( $pos2 === false )
		return false;
		
	$strFind = substr( $strHtml, $pos1, $pos2 - $pos1 );
	$pos1 =	strripos( $strFind, "<em>");
	if( $pos1 === false )
		return false;
		
	$precent = trim(substr( $strFind, $pos1 + strlen( "<em>" ) ));
	
	$pos2 = stripos( $strFind, "</em>" );
	if( $pos2 === false )
		return false;
		
	$strFind = substr( $strFind, 0, $pos2 );
	
	$pos1 =	strripos( $strFind, "<em>" );
	if( $pos1 === false )
		return false;
		
	$price = trim(substr( $strFind, $pos1 + strlen( "<em>" ) ));
	return true;
}

function get_precent_url( $strHtml, $pid )
{
	$pos1 = stripos( $strHtml, "id=\"txt_urlcode\"" );
	if( $pos1 === false )
		return "";
		
	$pos2 = stripos( $strHtml, ">", $pos1 );
	if( $pos2 === false)
		return "";
		
	$pos2 ++;
	$pos1 = stripos( $strHtml, "</textarea>", $pos2 );
	if( $pos1 === false )
		return "";
		
	$strUrl = substr( $strHtml, $pos2  , $pos1 - $pos2 );
	$pos1 = stripos( $strUrl, "&p=" );
	if( $pos1 === false )
		return "";
		
	$strLeft = substr( $strUrl, 0, $pos1);
	$strRight = substr( $strUrl, $pos1 + strlen( "&p=" ) );
	$pos1 = stripos( $strRight, "&" );
	
	if( $pos1 === false )
		return "";
	
	return $strLeft . $pid . substr( $strRight, $pos1 );
}

function get_item_discount( $item_id, $tbid, $type, $callback)
{
	$strHtml = file_get_contents( "http://taoke.alimama.com/spreader/gen_auction_code.htm?auction_id=".$item_id );
	
	$price = 0;
	$precent = 0;
	if( $strHtml != "" )
	{
		if( !get_precent( $strHtml, $item_id, $price, $precent ))
			return "$callback({\"code\":0});";
			
		$strUrl = get_precent_url( $strHtml, "&p=mm_24451165_0_0" );
		if( $strUrl == "")
			return "$callback({\"code\":0});";
			
		$strUrl .= "&p=mm_24451165_0_0&u=12175045".$tbid.",".$type;
		return "$callback({\"code\":1,\"price\":".$price.",\"precent\":".round($precent*0.6, 2).",\"url\":\"".$strUrl."\"});";
	}
	else
	{
		return "$callback({\"code\":0});";
	}
}

echo get_item_discount( $itemid, $tbid, $type, $callback);

?>